import { constantRouterMap } from '@/router'
import componentConfigs from '@/router/componentConfigs'
import { trim } from '@/utils'
import { getToken } from '@/utils/auth'

/**
 * 处理菜单数据，给只有一级的加一层
 * @param {*} menus
 */
function generateMenus(menus) {
  const menusRoute = []
  for (const i in menus) {
    const item = menus[i]
    const itemTemp = {
      path: '/a' + i,
      component: 'Layout',
      meta: {
        top: true,
        title: 'a' + i
      },
      hidden: item.hidden,
      name: '',
      children: [],
      iframeRender: (i === '0')
    }
    itemTemp.children.push(item)
    menusRoute.push(itemTemp)
  }
  return menusRoute
}

/**
 * 递归过滤异步路由表，返回用户权限菜单的路由表
 * @param {*} menus
 */
function generateAsyncRouter(menus) {
  const accessedRouters = []
  for (const item of menus) {
    const itemTemp = {}
    itemTemp.path = item.path
    if (typeof item.iframeRender !== 'undefined' && item.iframeRender === true) {
      itemTemp.iframeRender = true
    }
    if (item.name !== '') {
      itemTemp.name = item.name
    }
    itemTemp.hidden = item.hidden
    itemTemp.meta = item.meta
    item.component = trim(item.component) // trim component属性前后空格
    if (item.component !== '') {
      // 组件匹配
      const componentStr = item.component.replace(/\./g, '_').toUpperCase()
      const componentObj = componentConfigs[componentStr]
      itemTemp.component = componentObj
    }
    if (item.children && item.children.length) {
      // 递归调用
      itemTemp.children = generateAsyncRouter(item.children)
    }
    accessedRouters.push(itemTemp)
  }
  return accessedRouters
}

const permission = {
  state: {
    authRouters: [], //权限系统菜单
    routers: constantRouterMap,
    addRouters: [],
    iframeHref: '', //iframe模式引用的src
    sidebarTopActive: '1' //当前选中的头部导航
  },
  mutations: {
    // 运营系统路由
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    // 权限系统路由
    SET_AUTH_ROUTERS: (state, routers) => {
      state.authRouters = routers
    },
    SET_IFRAME_HREF: (state, url) => {
      state.iframeHref = url
    },
    SET_SIDEBAR_TOP_ACTIVE: (state, active) => {
      state.sidebarTopActive = active
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        // 运营管理平台菜单
        // const menus = data.menus.self
        // const menus = data.menus
        const menus = [
          {
            'path': '/account',
            'component': 'layout.inline',
            'hidden': false,
            'children': [
              // {
              //   'path': '/account/addUser',
              //   'component': 'account.addUser',
              //   'hidden': false,
              //   'meta': {
              //     'icon': 'user',
              //     'title': '添加用户',
              //     'handleAuth': {}
              //   },
              //   'name': 'AccountAddUser'
              // },
              {
                'path': '/account/password',
                'component': 'account.password',
                'hidden': false,
                'meta': {
                  'icon': 'password',
                  'title': '修改密码',
                  'handleAuth': {}
                },
                'name': 'AccountPassword'
              }
            ],
            'meta': {
              'icon': 'user',
              'title': '账户管理'
            },
            'name': 'Account'
          }
        ]

        const userId = getToken() * 1

        if (userId === 1) {
          menus[0].children.push({
            'path': '/account/addUser',
            'component': 'account.addUser',
            'hidden': false,
            'meta': {
              'icon': 'user',
              'title': '添加用户',
              'handleAuth': {}
            },
            'name': 'AccountAddUser'
          })

          menus[0].children.push({
            'path': '/account/accountList',
            'component': 'account.accountList',
            'hidden': false,
            'meta': {
              'icon': 'user',
              'title': '账户列表',
              'handleAuth': {}
            },
            'name': 'AccountList'
          })
        }

        // commit('SET_ROUTERS', menus)
        const menusRoute = generateMenus(menus)
        const accessedRouters = generateAsyncRouter(menusRoute)
        accessedRouters.push({ path: '*', redirect: '/404', hidden: true })
        commit('SET_ROUTERS', accessedRouters)
        // 集成权限系统菜单
        // const authMenus = data.menus.auth
        const authMenus = []
        commit('SET_AUTH_ROUTERS', authMenus)
        resolve()
      })
    },
    // 设置iframe的src
    SetIframeHref({ commit }, data) {
      return new Promise(resolve => {
        commit('SET_IFRAME_HREF', data)
        resolve()
      })
    },
    // 设置当前选中的头部导航
    SetSidebarTopActive({ commit }, data) {
      return new Promise(resolve => {
        commit('SET_SIDEBAR_TOP_ACTIVE', data)
        resolve()
      })
    }
  }
}

export default permission
